<?php
//封装函数
class MysqlCtrl
{
    //初始化参数
    //数据库参数配置
    static $dbms = "mysql";
    static $host = "localhost";
    static $user = "root";
    static $pass =  "root";
    static $database = "test";
    //睡眠时间
    static $sleep = 1;

    public $dsn = null;
    public $dbh = null;

    public function __construct()
    {
        $this->dsn = self::$dbms.":host=".self::$host.";dbname=".self::$database;
        //return $dsn;
        try {
              $this->dbh = new PDO($this->dsn, self::$user, self::$pass);
              echo "Connected\n";
        } catch (Exception $e) {
            echo $this->dsn;
              die("Unable to connect: " . $e->getMessage());
        }
    }
    
    //保存数据到数据库
    //PDO
    public function saveMySQL($arr)
    {

        try {  
              $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

              $this->dbh->beginTransaction();

              $count = count($arr);
              for ($i=0; $i < $count; $i++) { 
                  $this->dbh->exec($arr[$i]);
              }
        
              $this->dbh->commit();
          
        } catch (Exception $e) {
              $this->dbh->rollBack();
              echo "Failed: " . $e->getMessage()."\n";
              $json = json_encode($arr);
              echo "False-SQL: ".$json."\n";
              exit();
        }
    }
}